import { ICondition } from '../../interfaces';
import service from './service';

interface IDocDataStore {
	docDataStore: {
		[table_name: string]: {
			summary: { totalRow: number, totalPage: number },
			conditionCurrent: Array<{ [field_name: string]: any }>,
			paramCurrent: { [field_name: string]: any },
			pagingCurrent: { size: number, index: number },
			currentTimeMillis: { simpleDate: string, timeStamp: number },
			dataArray: Array<{ [field_name: string]: any }>
		}
	};
}

class Model {
	private flag_add = 4;
	private flag_upd = 8;
	private flag_del = 2;
	private crudlist: Array<{}>;
	private curdlist_add: Array<{}>;
	private curdlist_upd: Array<{}>;
	private curdlist_del: Array<{}>;

	private data: IDocDataStore;

	constructor(private spaceid: string, private table_name: string, private params: any) {
		this.init();
	}

	/**
	 * 执行查询
	 */
	public async query() {
		const data = await service<IDocDataStore>('dataservice.findbusidata', this.params, false, false);
		this.data = data;
		return this;
	}

	/**
	 * 获取总行数
	 */
	public total_row() {
		return this.data.docDataStore[this.table_name].summary.totalRow;
	}

	/**
	 * 获取总页数
	 */
	public total_page() {
		return this.data.docDataStore[this.table_name].summary.totalPage;
	}

	/**
	 * 获取每页显示数据条数
	 */
	public paging_size() {
		return this.data.docDataStore[this.table_name].pagingCurrent.size;
	}

	/**
	 * 获取当前页码
	 */
	public paging_index() {
		return this.data.docDataStore[this.table_name].pagingCurrent.index;
	}

	/**
	 * 获取执行服务时间
	 */
	public time_str() {
		return this.data.docDataStore[this.table_name].currentTimeMillis.simpleDate;
	}

	/**
	 * 获取执行服务时间戳
	 */
	public time_number() {
		return this.data.docDataStore[this.table_name].currentTimeMillis.timeStamp;
	}

	/**
	 * 获取一级表数据
	 */
	public first_data() {
		return this.data.docDataStore[this.table_name].dataArray;
	}

	/**
	 * 获取子表数据
	 * @param path 表路径，格式为：table_name._id(字段_id值).table_name
	 */
	// table_name._id.table_name._id.table_name
	public child_data(path: string) {
		const paths = path.split('.');
		let _data: any = null;
		paths.forEach((p, idx) => {
			if (idx === 0) {
				_data = this.data.docDataStore;
			}
			if (idx % 2 === 0) {
				// table_name
				const _table_name = p;
				_data = _data[_table_name] ? _data[_table_name].dataArray : null;
				if (_data === null) {
					throw Error('表名不存在～' + _table_name);
				}
			} else {
				const _id = p;
				if (_data) {
					const c_data = _data.filter((item: any) => {
						return item._id === _id;
					});
					if (c_data.length > 0) {
						_data = c_data[0];
					} else {
						_data = null;
					}
				}
				if (_data === null) {
					throw Error('字段_id值不存在～' + _id);
				}
			}
		});
		return _data;
	}

	/**
	 * 新增
	 * @param rowdata 行数据
	 * @param path 保存表路径，格式为：table_name._id(字段_id值).table_name
	 */
	public add(rowdata: { [field_name: string]: any }, path: string) {
		// TODO 传入的path中 _id 的值是否要验证必须存在
		const paths = path.split('.').map((p, idx) => {
			if (idx % 2 === 1) {
				return { key: '_id', value: p };
			} else {
				return p;
			}
		});
		if (paths.length % 2 === 0) {
			throw Error('新增数据传入的path必须为奇数=' + path);
		} else {
			const info = {
				flag: this.flag_add,
				path: paths,
				rowdata
			};
			this.curdlist_add.push(info);
			return this;
		}
	}

	/**
	 * 删除
	 * @param rowdata 行数据，删除条件
	 * @param path 删除表路径，格式为：table_name._id(字段_id值).table_name
	 */
	public del(rowdata: { [field_name: string]: any }, path: string) {
		// TODO 传入的path中 _id 的值是否要验证必须存在
		const paths = path.split('.').map((p, idx) => {
			if (idx % 2 === 1) {
				return { key: '_id', value: p };
			} else {
				return p;
			}
		});
		if (paths.length % 2 === 0) {
			throw Error('删除数据传入的path必须为奇数=' + path);
		} else {
			const info = {
				flag: this.flag_del,
				path: paths,
				rowdata
			};
			this.curdlist_del.push(info);
			return this;
		}
	}

	/**
	 * 编辑
	 * @param rowdata 行数据
	 * @param path 修改表路径，格式为：table_name._id(字段_id值).table_name._id(字段_id值)
	 */
	public upd(rowdata: { [field_name: string]: any }, path: string) {
		// TODO 传入的path中 _id 的值是否要验证必须存在
		const paths = path.split('.').map((p, idx) => {
			if (idx % 2 === 1) {
				return { key: '_id', value: p };
			} else {
				return p;
			}
		});
		if (paths.length % 2 === 1) {
			throw Error('修改数据传入的path必须为偶数=' + path);
		} else {
			const info = {
				flag: this.flag_upd,
				path: paths,
				rowdata
			};
			this.curdlist_upd.push(info);
			return this;
		}
	}

	/**
	 * 保存
	 */
	public async save() {
		this.crudlist = this.crudlist.concat(this.curdlist_add, this.curdlist_upd, this.curdlist_del);
		if (this.crudlist.length > 0) {
			const param = {
				crudlist: this.crudlist,
				modelid: this.params.modelid,
				refsystemid: this.params.refsystemid,
				spaceid: this.spaceid,
				systemid: this.params.systemid
			};
			const res = await service('dataservice.savebusidata', param, false, false);
			this.curdlist_add = [];
			this.crudlist = [];
			this.curdlist_del = [];
			this.curdlist_upd = [];
			return res;
		} else {
			return { result: {}, code: 1, msg: '保存成功' };
		}
	}

	private init() {
		this.curdlist_add = [];
		this.curdlist_del = [];
		this.curdlist_upd = [];
		this.crudlist = [];
	}
}

/**
 * 根据模型获取数据
 * @param url 请求地址
 * @param spaceid 项目spaceid
 * @param systemid 项目systemid
 * @param refsystemid 项目refsystemid
 * @param modelid 模型
 * @param table_name 表名，一级表名
 * @param condition 参数[可选参数],参数格式为{paging: {index: 1,size: 12},param: {},sort: {}}
 */
export default function get_model_data(spaceid: string, systemid: string, refsystemid: string, modelid: string, table_name: string, condition?: ICondition) {
	const param = {
		condition: condition || {
			paging: {
				index: 1,
				size: 12
			},
			param: {},
			sort: {}
		},
		emptydataflag: 0,
		modelid,
		refsystemid,
		spaceid,
		systemid
	};
	return new Model(spaceid, table_name, param);
}
